package com.util.web;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 解决跨域的问题
 */
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest requset, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)requset;
        HttpServletResponse resp=(HttpServletResponse)response;
        //转换请求编码
        req.setCharacterEncoding("UTF-8");
        String u=req.getParameter("username");
        String p=req.getParameter("password");
        String r=req.getParameter("randomcode");
        HttpSession session = req.getSession();
//    String validateCode = SessionUtil.getValidateCodeFromSession("validateCode");
//    String randomcode = req.getParameter("randomcode");
//    System.out.println(validateCode+"=="+randomcode);
        System.out.println("######################"+session.getId());
//          SessionUtil.setValToSession("validateCode", r);
        //session.setAttribute("validateCode",r);
//          Serializable id = SessionUtil.getSession().getId();
//          System.out.println("#######"+id);
//          SessionUtil.setValToSession("jsessionid",id);
//          resp.setHeader("Access-Control-Allow-Origin", "http://IP地址:8080");
//          resp.setHeader("Access-Control-Allow-Origin", "http://IP地址:3000");
        String origin = req.getHeader("Origin");
        System.out.println(origin);
     //   resp.setHeader("Access-Control-Allow-Origin", origin);
//        resp.setHeader("Access-Control-Allow-Origin", "*");
//        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
//        resp.setHeader("Access-Control-Max-Age", "3600");
//        resp.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,Content-Type");
//        resp.setHeader("Access-Control-Allow-Credentials", "true");
//        resp.setHeader("CORS_ORIGIN_ALLOW_ALL","true");
//        resp.setHeader("CORS_ALLOW_CREDENTIALS ","true");
//        resp.setContentType("text/html;charset=UTF-8");
//
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setContentType("text/html;charset=UTF-8");
        resp.setHeader("Access-Control-Allow-Headers", "Authentication,Origin,x-requested-with,Content-Type, Accept");


        if ("OPTIONS".equalsIgnoreCase(req.getMethod())){
            resp.setStatus(200);
            return;
        }
        chain.doFilter(requset, resp);
    }
    @Override
    public void destroy() {
    }
}